//
//  HPQualityIndexViewController.m
//  HPZZTong
//
//  Created by Handpay on 14-3-28.
//  Copyright (c) 2014年 Handpay. All rights reserved.
//

#import "HPQualityIndexViewController.h"
#import "HPConditionTextField.h"
#import "DefineUtil.h"
#import "ZZTongUtility.h"
#import "ZZTongPhotoButton.h"
#import "CSNValidator.h"


#define kProvinceViewTag  10001
#define kAreaViewTag      10002
#define kBranchViewTag    10003
#define kCardViewTag      10004

#define kCellH   44

@interface HPQualityIndexViewController (){
    BOOL isFirstLoad; // 第一次加载
    BOOL isFirstArea;
    IBOutlet UILabel *tipsLabel;
}
@property (retain, nonatomic) IBOutlet UILabel *cardTitleLabel;
@property(nonatomic, retain)NSArray* personDesArray;
@property(nonatomic, retain)NSArray* cardDesArray;
@property(nonatomic, retain)NSDictionary* bankDic;
@property(nonatomic, retain)NSDictionary* provinceDic;
@property(nonatomic, retain)NSDictionary* areaDic;
@property(nonatomic, retain)NSDictionary* branchDic;
@property(nonatomic, retain)NSArray* confirmValueArray;

@property (retain, nonatomic) IBOutlet UILabel *cardTipsLabel;
@property(nonatomic, retain)HPConditionTextField* nameTextField;
@property(nonatomic, retain)HPConditionTextField* certNoTextField;
@property(nonatomic, retain)HPConditionTextField* shopTextField;

@property(nonatomic, retain)HPConditionTextField* cardNoTextField;
@property(nonatomic, retain)HPConditionTextField* bankTextField;
@property(nonatomic, retain)HPDropDownListView* bankListView;
@property(nonatomic, retain)ZZTongAutoCompleteViewV2* branchView;
@property(nonatomic, retain)HPDropDownListView* provinceListView;
@property(nonatomic, retain)ZZTongAutoCompleteViewV2* areaView;
@property(nonatomic, retain)UIColor* textColor;
@property(nonatomic, retain) NSString* provinceFlag;
@property(nonatomic, retain) NSString* subBankFlag;
@property(nonatomic, retain) NSString* areaFlag;

@property(nonatomic, retain)UIView* cardBgView;


@end

@implementation HPQualityIndexViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.personDesArray = @[@{kDes: @"姓名", kPlaceHolder: @"请输入真实姓名", kFuncName:@"Name"},
                                @{kDes: @"身份证号码", kPlaceHolder: @"请输入身份证号码", kFuncName:@"CertNo"},
                                @{kDes: @"店铺名称", kPlaceHolder: @"请输入店铺名称", kFuncName:@"Shop"}];
//        self.bankDic = @{@"items":@(1),
//                         @"list":@[@{@"bankCode":ZZT_CLIENG.accountInfo.bankId,@"bankName":ZZT_CLIENG.accountInfo.bankName}]};
        self.cardDesArray = @[@{kDes: @"收款行", kPlaceHolder: @"", kFuncName:@"Bank"},
                              @{kDes: @"开户省份", kPlaceHolder: @"", kFuncName:@"Province"},
                              @{kDes: @"开户地市", kPlaceHolder: @"请输入开户地市名称", kFuncName:@"Area"},
                              @{kDes: @"开户行", kPlaceHolder: @"请输入开户行名称", kFuncName:@"Branch"},
                              @{kDes: @"银行卡号", kPlaceHolder: @"请输入卡号", kFuncName:@"CardNo"}];
        isFirstLoad = YES;
        isFirstArea = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    self.title = @"填写资质材料信息";
    self.textColor = kTitleFontColor;
    if (ZZT_CLIENG.accountInfo.accountStatus == AccountStatusFailed) {
        
        AccountInfoData* info = ZZT_CLIENG.accountInfo;
        self.confirmValueArray = @[info.name, info.certNo, info.shopName];
        
        self.errorView.hidden = NO;
        self.errorView.errorMsg = info.statusDescpriction;
        [self.errorView refresh];
        
        AccountInfoData* accountInfo = ZZT_CLIENG.accountInfo;
        NSMutableDictionary* dic = [[NSMutableDictionary alloc]initWithCapacity:10];
        [dic setObject:accountInfo.bankId forKey:@"bankCode"];
        [dic setObject:accountInfo.bankName forKey:@"bankName"];
        if (![NSString isNilOrEmpty:accountInfo.branchBankName]) {
            self.subBankFlag = @"1";
        }
        if (![NSString isNilOrEmpty:accountInfo.provinceName]) {
            self.provinceFlag = @"1";
        }
        if (![NSString isNilOrEmpty:accountInfo.areaName]) {
            self.areaFlag = @"1";
        }
        
        self.bankDic = @{@"items":@(1),
                         @"list":@[dic]};
        [dic release];
    }else{
        isFirstLoad = NO;
        isFirstArea = NO;
    }

    
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:NO];
    
    self.personTableView.dataSource = self;
    self.personTableView.delegate = self;
    
    [self.nextButton setBackgroundImage:[[UIImage imageNamed:@"bluebutton.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateNormal];
    
    [self.nextButton setBackgroundImage:[[UIImage imageNamed:@"bluebuttonhover.png"] stretchableImageWithLeftCapWidth:9 topCapHeight:0] forState:UIControlStateHighlighted];
    
    CGRect contentFrame = self.contentView.frame;
    if (!self.errorView.hidden) {
        contentFrame.origin.y = self.errorView.frame.origin.y + self.errorView.frame.size.height;
    }
    
    
    self.contentView.frame = contentFrame;
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, contentFrame.origin.y + contentFrame.size.height);
    
    if (self.screenData) {
        self.bankDic = screenData;
    }
    
    self.tabBarController.tabBar.hidden = YES;
    
    tipsLabel.textColor = kTitleFontColor;
    self.cardTipsLabel.textColor = kTitleFontColor;
    
    [self initCardView];
}
- (NSInteger)initCardView{
    NSInteger cardBgH = 2 * kCellH;
    UIView* cardBg = [[UIView alloc]initWithFrame:CGRectMake(0, 221, ScreenWidth, cardBgH)];
    cardBg.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:cardBg];
    self.cardBgView = cardBg;
    [cardBg release];
    
    NSInteger h = 42;
    NSInteger top = 0;
    
    CGRect labelRect = CGRectMake(15, 0, 100, h);
    CGRect valueRect = CGRectMake(110, 0, 200, h);
    CGRect lineRect = CGRectMake(0, h + 1, ScreenWidth, 1);
    UIColor* lineColor = RGBCOLOR(243, 243, 243);

    
    //收款行
    NSDictionary* valueDic = [self.cardDesArray objectAtIndex:0];
    
    UILabel* bankLabel = [[UILabel alloc] initWithFrame:labelRect];
    bankLabel.textColor = kNormalFontColor;
    bankLabel.font = kNormalFont;
    bankLabel.text = [valueDic objectForKey:kDes];
    [self.cardBgView addSubview:bankLabel];
    [bankLabel release];
    
    HPDropDownListView* dropListView = [[HPDropDownListView alloc] initWithFrame:CGRectMake(100, 0, 210, h)];
    [dropListView setPlaceholder:@"请选择银行"];
    [dropListView setShowColor:self.textColor];
    self.bankListView = dropListView;
    if (ZZT_CLIENG.accountInfo.bankName) {
        [self.bankListView setHPtext:ZZT_CLIENG.accountInfo.bankName];
    }
    self.bankListView.delegate = self;
    if (self.bankDic) {
        [self refreshList:@"bank"];
    }
    [self.cardBgView addSubview:dropListView];
    [dropListView release];
    
    //line
    UIView* blineView = [[UIView alloc]initWithFrame:lineRect];
    blineView.backgroundColor = lineColor;
    [self.cardBgView addSubview:blineView];
    [blineView release];
    
    top += kCellH;
    //province bgView
    UIView* provView = [[UIView alloc]initWithFrame:CGRectMake(0, top, ScreenWidth, kCellH)];
    provView.backgroundColor = [UIColor clearColor];
    provView.hidden = YES;
    provView.tag = kProvinceViewTag;
    
    valueDic = [self.cardDesArray objectAtIndex:1];
    UILabel* provinceLabel = [[UILabel alloc] initWithFrame:labelRect];
    provinceLabel.textColor = kNormalFontColor;
    provinceLabel.font = kNormalFont;
    provinceLabel.text = [valueDic objectForKey:kDes];
    [provView addSubview:provinceLabel];
    [provinceLabel release];
    
    HPDropDownListView* provListView = [[HPDropDownListView alloc] initWithFrame:CGRectMake(100, 0, 210, h)];
    [provListView setPlaceholder:@"请选择开户省份"];
    [provListView setShowColor:self.textColor];
    if (ZZT_CLIENG.accountInfo.provinceName) {
        [self.provinceListView setHPtext:ZZT_CLIENG.accountInfo.provinceName];
    }
    self.provinceListView = provListView;
    self.provinceListView.delegate = self;
    
    [provView addSubview:provListView];
    [provListView release];
    
    //line
    UIView* provlineView = [[UIView alloc]initWithFrame:lineRect];
    provlineView.backgroundColor = lineColor;
    [provView addSubview:provlineView];
    [provlineView release];
    
    [self.cardBgView addSubview:provView];
    [provView release];
    
    top += kCellH;
    //area bgView
    UIView* areaView = [[UIView alloc]initWithFrame:CGRectMake(0, top, ScreenWidth, kCellH)];
    areaView.backgroundColor = [UIColor clearColor];
    areaView.hidden = YES;
    areaView.tag = kAreaViewTag;
    
    valueDic = [self.cardDesArray objectAtIndex:2];
    UILabel* areaLabel = [[UILabel alloc] initWithFrame:labelRect];
    areaLabel.textColor = kNormalFontColor;
    areaLabel.font = kNormalFont;
    areaLabel.text = [valueDic objectForKey:kDes];
    [areaView addSubview:areaLabel];
    [areaLabel release];
    
    ZZTongAutoCompleteViewV2* areaAutoView = [[ZZTongAutoCompleteViewV2 alloc] initWithFrame:valueRect];
    [areaAutoView initViewStyle];
    [areaAutoView setHint:[valueDic objectForKey:kPlaceHolder]];
    [areaAutoView setTableWidth:ScreenWidth];
    areaAutoView.delegate = self;
    
    if (![NSString isNilOrEmpty:ZZT_CLIENG.accountInfo.areaName]) {
        [areaAutoView setText:ZZT_CLIENG.accountInfo.areaName];
    }
    
    [areaView addSubview:areaAutoView];
    self.areaView = areaAutoView;
    [areaAutoView release];
    
    //line
    UIView* arealineView = [[UIView alloc]initWithFrame:lineRect];
    arealineView.backgroundColor = lineColor;
    [areaView addSubview:arealineView];
    [arealineView release];
    
    [self.cardBgView addSubview:areaView];
    [areaView release];
    
    top += kCellH;
    //branch bgView
    UIView* branchBgView = [[UIView alloc]initWithFrame:CGRectMake(0, top, ScreenWidth, kCellH)];
    branchBgView.backgroundColor = [UIColor clearColor];
    branchBgView.hidden = YES;
    branchBgView.tag = kBranchViewTag;
    
    valueDic = [self.cardDesArray objectAtIndex:3];
    UILabel* branchLabel = [[UILabel alloc] initWithFrame:labelRect];
    branchLabel.textColor = kNormalFontColor;
    branchLabel.font = kNormalFont;
    branchLabel.text = [valueDic objectForKey:kDes];
    [branchBgView addSubview:branchLabel];
    [branchLabel release];
    
    ZZTongAutoCompleteViewV2* branchAutoView = [[ZZTongAutoCompleteViewV2 alloc] initWithFrame:valueRect];
    [branchAutoView initViewStyle];
    [branchAutoView setHint:[valueDic objectForKey:kPlaceHolder]];
    [branchAutoView setTableWidth:ScreenWidth];
    branchAutoView.delegate = self;
    
    if (![NSString isNilOrEmpty:ZZT_CLIENG.accountInfo.branchBankName]) {
        [branchAutoView setText:ZZT_CLIENG.accountInfo.branchBankName];
    }
    
    [branchBgView addSubview:branchAutoView];
    self.branchView = branchAutoView;
    [branchAutoView release];
    
    //line
    UIView* branchlineView = [[UIView alloc]initWithFrame:lineRect];
    branchlineView.backgroundColor = lineColor;
    [branchBgView addSubview:branchlineView];
    [branchlineView release];
    
    [self.cardBgView addSubview:branchBgView];
    [branchBgView release];
    
    top += kCellH;
    //bankcard bgView
    UIView* cardView = [[UIView alloc]initWithFrame:CGRectMake(0, kCellH, ScreenWidth, kCellH)];
    cardView.backgroundColor = [UIColor clearColor];
    cardView.tag = kCardViewTag;
    
    valueDic = [self.cardDesArray objectAtIndex:4];
    UILabel* cardLabel = [[UILabel alloc] initWithFrame:labelRect];
    cardLabel.textColor = kNormalFontColor;
    cardLabel.font = kNormalFont;
    cardLabel.text = [valueDic objectForKey:kDes];
    [cardView addSubview:cardLabel];
    [cardLabel release];
    
    HPConditionTextField* textField  = [[HPConditionTextField alloc] initWithFrame:valueRect];
    [textField setConditionType:HPConditionType_CardNo];
    textField.textColor = self.textColor;
    textField.font = kNormalFont;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.placeholder = [valueDic objectForKey:kPlaceHolder];
    [cardView addSubview:textField];
    self.cardNoTextField = textField;
    if (![NSString isNilOrEmpty:ZZT_CLIENG.accountInfo.cardNo]) {
        [textField setText:ZZT_CLIENG.accountInfo.cardNo];
    }
    
    [textField release];
    
    //line
    UIView* cardlineView = [[UIView alloc]initWithFrame:lineRect];
    cardlineView.backgroundColor = lineColor;
    [cardView addSubview:cardlineView];
    [cardlineView release];
    
    [self.cardBgView addSubview:cardView];
    [cardView release];
    
    return cardBgH;
}
- (void)refreshCardView{
    UIView* provView = [self.cardBgView viewWithTag:kProvinceViewTag];
    UIView* areaView = [self.cardBgView viewWithTag:kAreaViewTag];
    UIView* branchBgView = [self.cardBgView viewWithTag:kBranchViewTag];
    UIView* cardView = [self.cardBgView viewWithTag:kCardViewTag];

    provView.hidden = YES;
    areaView.hidden = YES;
    branchBgView.hidden = YES;
    
    NSInteger top = kCellH;
    if (![NSString isNilOrEmpty:self.provinceFlag] && [self.provinceFlag isEqualToString:@"1"]) {
        provView.hidden = NO;
        top += kCellH;
    }
    
    if (![NSString isNilOrEmpty:self.areaFlag] && [self.areaFlag isEqualToString:@"1"]) {
        areaView.hidden = NO;
        CGRect frame = areaView.frame;
        frame.origin.y = top;
        areaView.frame = frame;
        top += kCellH;
    }
    if (![NSString isNilOrEmpty:self.subBankFlag] && [self.subBankFlag isEqualToString:@"1"]) {
        branchBgView.hidden = NO;
        CGRect frame = branchBgView.frame;
        frame.origin.y = top;
        branchBgView.frame = frame;
        top += kCellH;
    }
    CGRect frame = cardView.frame;
    frame.origin.y = top;
    cardView.frame = frame;
    top += kCellH;
    
    frame = self.cardBgView.frame;
    frame.size.height = top;
    self.cardBgView.frame = frame;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)dealloc {
    self.personDesArray = nil;
    self.cardDesArray = nil;
    self.bankDic = nil;
    self.provinceDic = nil;
    self.areaDic = nil;
    self.branchDic = nil;
    self.confirmValueArray = nil;
    
    self.nameTextField = nil;
    self.certNoTextField = nil;
    self.shopTextField = nil;
    
//    self.branchTextField = nil;
    self.cardNoTextField = nil;
    self.bankListView = nil;
    self.bankTextField = nil;
    self.branchView = nil;
    
    self.provinceListView = nil;
//    self.areaTextField = nil;
    self.areaView = nil;
    
    self.textColor = nil;
    
    self.cardBgView = nil;
    
    self.provinceFlag = nil;
    self.subBankFlag = nil;
    self.areaFlag = nil;
    
    [_personTableView release];
    [_nextButton release];
    [_remindView release];
    [_contentView release];
    [_errorView release];
    [_scrollView release];
    [_cardTipsLabel release];
    [_cardTitleLabel release];
    [tipsLabel release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setPersonTableView:nil];
    [self setNextButton:nil];
    [self setContentView:nil];
    [self setRemindView:nil];
    [self setErrorView:nil];
    [self setScrollView:nil];
    [self setCardTipsLabel:nil];
    [self setCardTitleLabel:nil];
    [super viewDidUnload];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)initPersonTableViewCell:(NSInteger)index{
    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    NSDictionary* valueDic = [self.personDesArray objectAtIndex:index];
    
    UILabel* desLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 44)];
    desLabel.textColor = kNormalFontColor;
    desLabel.font = kNormalFont;
    desLabel.text = [valueDic objectForKey:kDes];
    [cell addSubview:desLabel];
    
    HPConditionTextField* textField = [[HPConditionTextField alloc] initWithFrame:CGRectMake(110, 0, 200, 44)];
    textField.textColor = self.textColor;
    textField.font = kNormalFont;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.placeholder = [valueDic objectForKey:kPlaceHolder];
    if (index == 0 || index== 2) {
        [textField setConditionType:HPConditionType_Deafult];
    }
    if (ZZT_CLIENG.accountInfo.accountStatus == AccountStatusFailed) {
        textField.text = [self.confirmValueArray objectAtIndex:index];
    }
    SEL selector = NSSelectorFromString([NSString stringWithFormat:@"set%@TextField:", [valueDic objectForKey:kFuncName]]);
    [self performSelector:selector withObject:textField];
    
    [cell addSubview:textField];
    [textField release];
    
    [desLabel release];
    
    return [cell autorelease];
}

- (void)searchWordChanged:(ZZTongAutoCompleteViewV2*)view word:(NSString*)word{
    isFirstLoad = NO;
    isFirstArea = NO;
    
    if ([NSString isNilOrEmpty:word]){
        [view changeSearchArray:nil];
        return;
    }
    NSNumber* indexNum = (NSNumber*)[self.bankListView readHPselectedindex];
    if (!indexNum) {
        return;
    }
    
    NSInteger indexBank = [indexNum integerValue];
    if (indexBank < 0) {
        return;
    }
    NSString* bankId = [[[self.bankDic objectForKey:@"list"] objectAtIndex:indexBank] objectForKey:@"bankCode"];
    
    if (!bankId) {
        [view changeSearchArray:nil];
        return;
    }
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    NSDictionary* params = @{@"bankCode": bankId,
                             @"searchText": word,
                             KEY_CHANNEL: [zzt getChannel],
                             @"pageSize":@"30"
                             };
    
    if([view isEqual:self.areaView]){
        NSInteger indexProvince = -1;
        NSNumber* indexProNumber = (NSNumber*)[self.provinceListView readHPselectedindex];
        if (indexProNumber) {
            indexProvince = [indexProNumber integerValue];
        }
        NSString* provinceId = nil;
        if (indexProvince >= 0) {
            provinceId = [[[self.provinceDic objectForKey:@"list"] objectAtIndex:indexProvince] objectForKey:@"provinceId"];
        }
       
        NSMutableDictionary* mutParams = [NSMutableDictionary dictionaryWithDictionary:params];
        if (provinceId) {
            [mutParams setObject:provinceId forKey:@"provinceId"];
        }
        LOG(@"params:%@", mutParams);
        [zzt.netEngine sendRequest:NET_ACTION_BANK_AREA withParams:mutParams withDelegate:self];
    }else if([view isEqual:self.branchView]){
        LOG(@"params:%@", params);
        [zzt.netEngine sendRequest:NET_ACTION_GET_BRANCHS withParams:params withDelegate:self];
    }
}
- (NSInteger)listSelectedId:(HPDropDownListView*)listView{
    NSInteger index = 0;
    if (listView) {
        NSNumber* selectId = (NSNumber*)[listView readHPselectedindex];
        if (selectId) {
            index = selectId.intValue;
            if (index < 0) {
                index = 0;
            }
        }
    }
    return index;
}
- (void)refreshUI{
    CGRect frame = self.cardTipsLabel.frame;
    CGRect personFrame = self.personTableView.frame;
    frame.origin.y = personFrame.origin.y + personFrame.size.height + 24;
    self.cardTipsLabel.frame = frame;
    
    CGRect titleFrame = self.cardTitleLabel.frame;
    titleFrame.origin.y = frame.origin.y - 4;
    self.cardTitleLabel.frame = titleFrame;
    
    CGRect cardFrame = self.cardBgView.frame;
    cardFrame.origin.y = frame.origin.y + frame.size.height + 6;
    self.cardBgView.frame = cardFrame;
    
    frame = self.remindView.frame;
    frame.origin.y = cardFrame.origin.y + cardFrame.size.height + 5;
    self.remindView.frame = frame;
    
    frame = self.nextButton.frame;
    frame.origin.y = self.remindView.frame.origin.y + self.remindView.frame.size.height + 15;
    self.nextButton.frame = frame;
    
    frame = self.contentView.frame;
    frame.size.height = self.nextButton.frame.origin.y + self.nextButton.frame.size.height + 15;
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.nextButton.frame.origin.y + self.nextButton.frame.size.height + 10);
    self.contentView.frame = frame;
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, frame.size.height + frame.origin.y);
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = nil;
    if ([tableView isEqual:self.personTableView]) {
        cell = [self initPersonTableViewCell:indexPath.row];
    }
    return cell;
}
- (void)refreshList:(NSString*)keyId{
    
    NSDictionary* dataDic = nil;
    NSString* nameKey = nil;
    NSString* idKey = nil;
    NSString* sourId = nil;
    HPDropDownListView* listView = nil;
    
    if ([keyId isEqualToString:@"province"]) {
        listView = self.provinceListView;
        dataDic = self.provinceDic;
        nameKey = @"provinceName";
        idKey = @"provinceId";
        
        if (isFirstLoad) {
            sourId = ZZT_CLIENG.accountInfo.provinceId;
        }
        isFirstLoad = NO;
    }else if ([keyId isEqualToString:@"bank"]) {
        listView = self.bankListView;
        dataDic = self.bankDic;
        nameKey = @"bankName";
        idKey = @"bankCode";
        sourId = ZZT_CLIENG.accountInfo.bankId;
    }
    
    if (listView) {
        NSInteger count = [[dataDic objectForKey:@"items"] integerValue];
        NSArray* bankArray = [dataDic objectForKey:@"list"];
        
        NSMutableArray* itemsArray = nil;
        NSInteger index = -1;
        if (bankArray && bankArray.count == count) {
            itemsArray = [NSMutableArray array];
            
            for (NSInteger i = 0; i < bankArray.count; i++) {
                NSDictionary* dic = [bankArray objectAtIndex:i];
                [itemsArray addObject:[dic objectForKey:nameKey]];
                if (sourId) {
                    NSString* tempId = [dic objectForKey:idKey];
                    if ([tempId isEqualToString:sourId]) {
                        index = i;
                    }
                }
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^(){
            [listView setHPitems:itemsArray];
            if (index != -1) {
                [listView setHPselectedindex:@(index + 1)];
            }
            [self refreshCardView];
            [self refreshUI];
        });
    }
}

- (void)parseGetBanks:(NSDictionary *)respData{
    self.bankDic = respData;
    [self refreshList:@"bank"];
}
- (void)parseGetProvince:(NSDictionary *)respData{
    self.provinceDic = respData;
    
    [self refreshList:@"province"];
}
- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    [HPUIENG removeWaiting];
    if ([action isEqualToString:NET_ACTION_UPLOAD_UCINFO]){
        [self gotoPhotoScreen];
    }else if ([action isEqualToString:NET_ACTION_GET_BRANCHS]){
        [self parseGetBranchs:respData];
    }else if ([action isEqualToString:NET_ACTION_BANK_PROVINCE]){
        [self parseGetProvince:respData];
    }else if ([action isEqualToString:NET_ACTION_BANK_AREA]){
        [self parseGetArea:respData];
    }
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    if ([action isEqualToString:NET_ACTION_GET_BRANCHS]) {
        self.branchDic = nil;
        dispatch_async(dispatch_get_main_queue(), ^(){
            [self.branchView changeSearchArray:nil];
        });
    }else if ([action isEqualToString:NET_ACTION_BANK_AREA]) {
        self.areaDic = nil;
        dispatch_async(dispatch_get_main_queue(), ^(){
            [self.areaView changeSearchArray:nil];
        });
    }else if ([action isEqualToString:NET_ACTION_BANK_PROVINCE]) {
        self.provinceDic = nil;
        dispatch_async(dispatch_get_main_queue(), ^(){
            [self refreshList:@"province"];
        });
    }
}
- (void)parseGetArea:(NSDictionary *)respData{
    self.areaDic = respData;
    
    NSInteger count = [[respData objectForKey:@"items"] integerValue];
    NSArray* branchArray = [respData objectForKey:@"list"];
    
    NSMutableArray* itemsArray = nil;
    
    if (branchArray && branchArray.count == count) {
        itemsArray = [NSMutableArray array];
        
        for (NSDictionary* dic in branchArray) {
            [itemsArray addObject:[dic objectForKey:@"areaName"]];
        }
    }
    
    dispatch_async(dispatch_get_main_queue(), ^(){
        [self.areaView changeSearchArray:itemsArray];
    });
}
- (void)parseGetBranchs:(NSDictionary *)respData{
    self.branchDic = respData;
    
    NSInteger count = [[respData objectForKey:@"items"] integerValue];
    NSArray* branchArray = [respData objectForKey:@"list"];
    
    NSMutableArray* itemsArray = nil;
    
    if (branchArray && branchArray.count == count) {
        itemsArray = [NSMutableArray array];
        
        for (NSDictionary* dic in branchArray) {
            [itemsArray addObject:[dic objectForKey:@"subBankName"]];
        }
    }
    
    dispatch_async(dispatch_get_main_queue(), ^(){
        [self.branchView changeSearchArray:itemsArray];
    });
}

- (void)gotoPhotoScreen{
    NSDictionary* params = [self orgPersonDic];
    if (!params) {
        return;
    }
    if (self.screenData) {
        NSString* scrName = [self.screenData objectForKey:KEY_SCREEN_NAME];
        if (![NSString isNilOrEmpty:scrName]) {
            NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithDictionary:params];
            [dic setObject:scrName forKey:KEY_SCREEN_NAME];
            [HPUIENG showScreen:SCR_QUALITY_PHOTO params:dic];
            return;
        }
        
        
    }
    [HPUIENG showScreen:SCR_QUALITY_PHOTO params:params];
}

- (void)sendConfirmReq:(NSDictionary*)personDic{
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    NSString * csn = [[NSUserDefaults standardUserDefaults] objectForKey:QualityCSN];
    
    NSDictionary* params = @{KEY_PHONE: DES_ENC(zzt.accountInfo.mobile),
                             @"name": DES_ENC([personDic objectForKey:@"name"]),
                             @"certNo": DES_ENC([personDic objectForKey:@"certNo"]),
                             @"shopName": DES_ENC([personDic objectForKey:@"shopName"]),
                             @"cardNum": DES_ENC([[personDic objectForKey:@"cardNo"] stringByReplacingOccurrencesOfString:@" " withString:@""]),
                             @"bankCode": [personDic objectForKey:@"bankCode"],
                             @"type": @"0",
                             @"imageType": @"",
                             KEY_CHANNEL: [zzt getChannel],
                             
                             KEY_LOCATION:[CSNValidator getLocation],
                             KEY_ADDRESS:[CSNValidator getAddress],
                             KEY_CSN : DES_ENC(csn),
                             KEY_NEWBANK_FLAG:@"1",
                             @"newBankFlag":@"1"
                             };
    NSMutableDictionary* mutParams = [NSMutableDictionary dictionaryWithDictionary:params];
    NSString* subBankCode = [personDic objectForKey:@"subBankCode"];
    NSDictionary* provinceInfo = [personDic objectForKey:@"provinceInfo"];
    NSString* areaId = [personDic objectForKey:@"areaId"];
    if (subBankCode) {
        [mutParams setObject:subBankCode forKey:@"subBankCode"];
    }
    if (provinceInfo) {
        NSString* provinceId = [provinceInfo objectForKey:@"provinceId"];
        [mutParams setObject:provinceId forKey:@"provinceId"];
    }
    if (areaId) {
        [mutParams setObject:areaId forKey:@"areaId"];
    }
    
    LOG(@"params:%@", mutParams);
    [zzt.netEngine sendRequest:NET_ACTION_UPLOAD_UCINFO withParams:mutParams withDelegate:self];
    
    [zzt.uiEngine showNetWaiting];
}

- (IBAction)nextButtonClick:(id)sender {
    NSDictionary* param = [self orgPersonDic];
    if (!param) {
        return;
    }
    
    [CSNValidator validateCSNAndExcuteBlock:^(HPSwiperResult *swiperResult) {
        if (swiperResult.isSuccess || SwiperService.csnStatus == CSNStatusUnbound)
        {
            [[NSUserDefaults standardUserDefaults] setObject:SwiperService.csn forKey:QualityCSN];
            if (SwiperService.csnStatus == CSNStatusUnbound && ZZT_CLIENG.accountInfo.accountStatus != AccountStatusSuccess)
            {
                [[NSUserDefaults standardUserDefaults] setObject:SwiperService.csn forKey:BindCSN];
            }
            else
            {
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:BindCSN];
            }
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self sendConfirmReq:param];
        }
        else
        {
            [HPUIENG showAlert:swiperResult.message];
        }
    } autoTip:NO];
}

- (NSDictionary*)orgPersonDic{

    if (![ZZTongUtility checkIsInput:self.nameTextField tips:@"真实姓名"]) {
        return nil;
    }
    
    if (![ZZTongUtility checkLength:self.nameTextField tips:@"真实姓名最大长度不能超过25位" minLen:0 maxLen:25]) {
        return nil;
    }
   
    if (![ZZTongUtility checkIsInput:self.certNoTextField tips:@"身份证号"]) {
        return nil;
    }
    
    NSString* certNo = self.certNoTextField.text;
    NSString* msg = [Utility IDCardValidate:certNo];
    if (msg) {
        [HPUIENG showAlert:msg];
        return nil;
    }
    
    if (![ZZTongUtility checkIsInput:self.shopTextField tips:@"店铺名称"]) {
        return nil;
    }
    
    if (![ZZTongUtility checkLength:self.shopTextField tips:@"店铺名称最大长度不能超过30位" minLen:0 maxLen:30]) {
        return nil;
    }
    
    //收款行
    if (!self.bankDic) {
        [HPUIENG showAlert:@"请选择收款行"];
        return nil;
    }
    
    NSNumber* indexNum = (NSNumber*)[self.bankListView readHPselectedindex];
    NSInteger index = [indexNum integerValue];
    if (index == -1) {
        [HPUIENG showAlert:@"请选择银行"];
        return nil;
    }
    
    NSDictionary* bankInfo = [[self.bankDic objectForKey:@"list"] objectAtIndex:index];
    if (!bankInfo) {
        [HPUIENG showAlert:@"请选择银行"];
        return nil;
    }
    
    AccountInfoData* accountInfo = ZZT_CLIENG.accountInfo;
    //开户省份
    NSDictionary* provinceInfo = nil;
    if (![NSString isNilOrEmpty:self.provinceFlag] && [self.provinceFlag isEqualToString:@"1"]) {
        if (!self.provinceDic) {
            [HPUIENG showAlert:@"请选择开户省份"];
            return nil;
        }
        
        indexNum = (NSNumber*)[self.provinceListView readHPselectedindex];
        index = [indexNum integerValue];
        if (index == -1) {
            [HPUIENG showAlert:@"请选择开户省份"];
            return nil;
        }
        
        provinceInfo = [[self.provinceDic objectForKey:@"list"] objectAtIndex:index];
        if (!provinceInfo) {
            [HPUIENG showAlert:@"请选择开户省份"];
            return nil;
        }

    }
    
    //开户地市
    NSString* subAreaId = nil;
    NSString* area = nil;
    if (![NSString isNilOrEmpty:self.areaFlag] && [self.areaFlag isEqualToString:@"1"]) {
        area = [self.areaView readText];
        
        if ([NSString isNilOrEmpty:area]) {
            [HPUIENG showAlert:@"请输入开户地市"];
            return nil;
        }
        
        if (!self.areaDic) {
            subAreaId = accountInfo.areaId;
        }else{
            BOOL isFound = NO;
        
            NSArray* areaArray = [self.areaDic objectForKey:@"list"];
            for (NSDictionary* areaInfo in areaArray) {
                NSString* name = [areaInfo objectForKey:@"areaName"];
                if ([name isEqualToString:area]) {
                    isFound = YES;
                    subAreaId = [areaInfo objectForKey:@"areaId"];
                    break;
                }
            }
        
            if (!isFound) {
                [HPUIENG showAlert:@"请输入正确的开户地市"];
                return nil;
            }
        }
    }
    NSString* branch = nil;
    NSString* subBankId = nil;
    //开户行
    if (![NSString isNilOrEmpty:self.subBankFlag] && [self.subBankFlag isEqualToString:@"1"]){
        branch = [self.branchView readText];
        if ([NSString isNilOrEmpty:branch]) {
            [HPUIENG showAlert:@"请输入开户行"];
            return nil;
        }
        if (!self.branchDic) {
            subBankId = accountInfo.branchBankId;
        }else{
            BOOL isFound = NO;
        
            NSArray* branchArray = [self.branchDic objectForKey:@"list"];
            for (NSDictionary* branchInfo in branchArray) {
                NSString* name = [branchInfo objectForKey:@"subBankName"];
                if ([name isEqualToString:branch]) {
                    isFound = YES;
                    subBankId = [branchInfo objectForKey:@"subBankCode"];
                    break;
                }
            }
        
            if (!isFound) {
                [HPUIENG showAlert:@"请输入正确的开户行"];
                return nil;
            }
        }
    }
    
    NSString* tempCardNo = [self.cardNoTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![ZZTongUtility checkIsInput:self.cardNoTextField tips:@"银行卡号"]) {
        return nil;
    }
    
    if (![Utility isLegalCard:tempCardNo length:0]) {
        [HPUIENG showAlert:@"请输入正确的银行卡号"];
        return nil;
    }
    
    NSDictionary* params = @{@"name": self.nameTextField.text,
                             @"certNo": self.certNoTextField.text,
                             @"shopName": self.shopTextField.text,
                             @"bankName": [bankInfo objectForKey:@"bankName"],
                             @"bankCode": [bankInfo objectForKey:@"bankCode"],
                             @"cardNo": tempCardNo};
    
    NSMutableDictionary* mutParams = [[[NSMutableDictionary alloc]initWithDictionary:params]autorelease];
    
    if (provinceInfo) {
        [mutParams setObject:provinceInfo forKey:@"provinceInfo"];
    }
    
    if (branch) {
        [mutParams setObject:branch forKey:@"subBankName"];
    }
    if (subBankId) {
        [mutParams setObject:subBankId forKey:@"subBankCode"];
    }
    if (area) {
        [mutParams setObject:area forKey:@"areaName"];
    }
    if (subAreaId) {
        [mutParams setObject:subAreaId forKey:@"areaId"];
    }
    
    [self.nameTextField resignFirstResponder];
    [self.certNoTextField resignFirstResponder];
    [self.shopTextField resignFirstResponder];
    [self.branchView.contentTextField resignFirstResponder];
    [self.cardNoTextField resignFirstResponder];
    return mutParams;
}

- (void)sendProvinceReq{
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    NSInteger index = [self listSelectedId:self.bankListView];
    NSString* bankCode = [[[self.bankDic objectForKey:@"list"] objectAtIndex:index] objectForKey:@"bankCode"];
    NSDictionary* params = @{KEY_CHANNEL: [zzt getChannel],
                             @"bankCode": bankCode,
                             @"pageSize": @"0"};
    LOG(@"params:%@", params);
    [zzt.netEngine sendRequest:NET_ACTION_BANK_PROVINCE withParams:params withDelegate:self];
    
    [zzt.uiEngine showNetWaiting];
}

- (void) dropDownListView:(HPDropDownListView *)dropDownListView selected:(NSArray *)indexs texts:(NSArray *)texts{
    if ([dropDownListView isEqual:self.bankListView]) {
        if (!isFirstLoad) {
            if (self.branchView) {
                [self.branchView setText:@""];
            }
            if (self.areaView) {
                [self.areaView setText:@""];
            }
            if (self.provinceListView) {
                [self.provinceListView setHPtext:@""];
            }
        }
//        isFirstLoad = NO;
        NSInteger index = [self listSelectedId:self.bankListView];
        self.provinceFlag = [[[self.bankDic objectForKey:@"list"] objectAtIndex:index] objectForKey:@"provinceFlag"];
        self.subBankFlag = [[[self.bankDic objectForKey:@"list"] objectAtIndex:index] objectForKey:@"subBankFlag"];
        self.areaFlag = [[[self.bankDic objectForKey:@"list"] objectAtIndex:index] objectForKey:@"areaFlag"];
        
        if (![NSString isNilOrEmpty:self.provinceFlag] && [self.provinceFlag isEqualToString:@"1"]) {
            [self sendProvinceReq];
            return;
        }
        isFirstLoad = NO;
    }else if([dropDownListView isEqual:self.provinceListView]){
        if (!isFirstArea) {
            if (self.areaView) {
                [self.areaView setText:@""];
            }
        }
        isFirstArea = NO;
        if (![NSString isNilOrEmpty:self.areaFlag] && [self.areaFlag isEqualToString:@"1"]) {
            
        }
    }
    [self refreshCardView];
    [self refreshUI];
}
@end
